package com.wenjie.terminal.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ForwardToSettingsCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ForwardScope;
import com.wenjie.terminal.interfaces.PermissionResultService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 权限申请工具类
 * <a href="https://github.com/guolindev/PermissionX">文档地址</a>
 */
public class PermissionUtil {

    private final Context context;

    public PermissionUtil(Context context) {
        this.context = context;
    }

    /**
     * 获取应用声明的所有权限
     */
    public String[] getDeclaredPermissions() {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(),
                    PackageManager.GET_PERMISSIONS
            );

            String[] requestedPermissionsArray = packageInfo.requestedPermissions;
            String[] targetPermissionArray;
            if (requestedPermissionsArray != null) {
                ArrayList<String> permissionList = new ArrayList<>(Arrays.asList(requestedPermissionsArray));

                final String SERVICE_MESSAGE = "android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING";
                permissionList.remove(SERVICE_MESSAGE);

                final String USB_PERMISSION = "android.permission.USB_PERMISSION";
                permissionList.remove(USB_PERMISSION);

                targetPermissionArray = permissionList.toArray(new String[0]);
            } else {
                targetPermissionArray = new String[0];
            }

            return targetPermissionArray;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return new String[0];
        }
    }

    /**
     * 检查权限
     */
    public void checkPermission(FragmentActivity activity, PermissionResultService callback) {
        // 获取应用声明的所有权限
        String[] permissions = getDeclaredPermissions();

        if (permissions.length == 0) {
            return;
        }

        PermissionX.init(activity)
                .permissions(permissions)
                .onForwardToSettings(new ForwardToSettingsCallback() {
                    @Override
                    public void onForwardToSettings(@NonNull ForwardScope scope, @NonNull List<String> deniedList) {
                        scope.showForwardToSettingsDialog(deniedList, "是否要前往应用设置页面授予相关权限？", "确定", "取消");
                    }
                })
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, @NonNull List<String> grantedList, @NonNull List<String> deniedList) {
                        if (allGranted) {
                            // 如果已经拥有了全部权限，则判断应用是否在电池优化名单中，如果是，打开设置界面让用户将其移除
                            BatteryOptimizationUtil.checkAndOpenBatteryOptimizationSettings(context);

                            callback.applyResult(true, null);
                        } else {
                            if (!deniedList.isEmpty()) {
                                // “显示在其他界面上方”的权限申请有问题，这里手动跳转到设置界面
                                if (deniedList.contains("android.permission.SYSTEM_ALERT_WINDOW")) {
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                                    context.startActivity(intent);
                                }
                            }

                            callback.applyResult(false, "没有获取到全部权限，请退出应用并到设置应用中手动授予权限");
                        }
                    }
                });
    }
}
